<template>
  <div class="app-container">
    <div
      class="filter-container"
      style="display:flex;justify-content: flex-end;"
    >
      <!-- <el-input
        v-model="searchInpt"
        placeholder="输入关键词"
        clearable
        @keyup.enter.native="search()"
        class="search-btn"
      >
        <el-button
          @click="search()"
          icon="el-icon-search"
          :loading="searchLoading"
          slot="append"
        >搜索</el-button>
      </el-input> -->
      <!-- <div class="float-right"> -->
      <el-button
        type="primary"
        @click="newQA()"
      >新增看一看</el-button>
      <!-- </div> -->
    </div>
    <div class="table-container">
      <Table :table="dataTable">
        <template
          slot-scope="props"
          slot="picUrl"
        >
          <el-button
            type="text"
            @click="showImgDialogBox(props.obj.row.picUrl)"
            size="small"
          >查看</el-button>
        </template>
        <template
          slot-scope="props"
          slot="content"
        >
          <span v-if="!props.obj.row.showAll">{{props.obj.row.content.substring(0,10)+'...'}}</span>
          <span v-else>{{props.obj.row.content}}</span>
          <el-button
            type="text"
            size="small"
            @click="props.obj.row.showAll = !props.obj.row.showAll"
          >{{!props.obj.row.showAll?'展开':'收起'}}</el-button>
        </template>
        <template
          slot-scope="props"
          slot="action"
        >
          <el-button
            type="text"
            size="small"
            @click="delQA(props.obj.row.id)"
          >删除</el-button>
        </template>
      </Table>
      <div
        class="Pagination"
        style="text-align: left;margin-top: 10px;"
      >
        <el-pagination
          v-if="pageshow"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="limit"
          layout="total, prev, pager, next"
          :total="count"
        >
        </el-pagination>
      </div>
    </div>

    <el-dialog
      title="新建看一看"
      :visible.sync="addNewQA"
      width="30%"
      center
    >

      <el-form
        :model="newLookdata"
        :rules="newQAdataRules"
        ref="newLookdata"
        label="100px"
      >
        <el-form-item
          label="标题"
          prop="title"
        >
          <el-input
            type="text"
            v-model="newLookdata.title"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="内容"
          prop="content"
        >
          <el-input
            type="textarea"
            v-model="newLookdata.content"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="链接"
          prop="linkUrl"
        >
          <el-input
            type="input"
            v-model="newLookdata.linkUrl"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="阅读数"
          prop="readCount"
        >
          <el-input
            type="input"
            v-model="newLookdata.readCount"
          ></el-input>
        </el-form-item>
        <el-form-item label="上传图片">
          <el-upload
            ref="upload"
            v-model="newLookdata.pictureUrl"
            class="upload-demo"
            :action="uploadUrl"
            :on-remove="handleRemove"
            name="files"
            :on-success="handleAvatarSuccess"
            list-type="picture"
            multiple
          >
            <el-button
              size="small"
              type="primary"
            >选择图片</el-button>
            <!-- <div
                  slot="tip"
                  class="el-upload__tip"
                >只能上传jpg/png文件，且不超过500kb</div> -->
          </el-upload>
        </el-form-item>
      </el-form>

      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="addNewQA = false">取 消</el-button>
        <el-button
          type="primary"
          @click="handleSubmit('newLookdata')"
        >确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="存档内容"
      :visible.sync="showImgDialog"
      top="4%"
      width="40%"
    >
      <div class="demo-image__lazy">
        <div
          v-for="(pic,index) in picture"
          :key="index"
        >
          <vue-photo-zoom-pro :url="pic"></vue-photo-zoom-pro>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  fetchLookList,
  fetchDeleteLook,
  fetchAddLook,
  fetchUploadImg
} from "@/api/table";
import format from "date-format";
import Table from "@/components/Table";
import { getToken } from "@/utils/auth";
export default {
  data() {
    // const validateUpload = (rule, value, callback) => {
    //   console.log(rule);
    //   if (
    //     this.newLookdata.pictureUrl &&
    //     this.newLookdata.pictureUrl.length === 0
    //   ) {
    //     callback(new Error("请上传图片"));
    //   } else {
    //     callback();
    //   }
    // };
    return {
      //总页码
      count: 0,
      //单页行数
      limit: 20,
      //页码
      currentPage: 1,
      searchInpt: "",
      searchLoading: false,
      pageshow: true,
      uploadUrl: "",
      //上传图片
      fileList2: [],
      imgHeaders: {
        Authorization: ""
      },
      dataTable: {
        loading: false,
        border: true,
        hasOperation: false,
        tr: [
          {
            id: "1",
            label: "id",
            prop: "id",
            show: true
          },
          {
            id: "2",
            label: "标题",
            prop: "title",
            show: true
          },
          {
            id: "3",
            label: "阅读数",
            prop: "readCount",
            show: true
          },
          {
            id: "5",
            label: "创建时间",
            prop: "createTime",
            show: true
          },
          {
            id: "6",
            label: "内容",
            prop: "content",
            show: "template"
          },
          {
            id: "7",
            label: "图片",
            prop: "picUrl",
            show: "template"
          },
          {
            id: "8",
            label: "状态",
            prop: "status",
            show: true
          },
          {
            id: "9",
            label: "操作",
            prop: "action",
            show: "template"
          }
        ],
        data: [],
        operation: {}
      },
      searchInpt: "",
      picture: "",
      addNewQA: false,
      showImgDialog: false,
      newLookdata: {
        title: "",
        content: "",
        linkUrl: "",
        pictureUrl: [],
        readCount: ""
      },
      newQAdataRules: {
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        linkUrl: [{ required: true, message: "链接不能为空", trigger: "blur" }],
        content: [{ message: "内容不能为空", trigger: "blur" }],
        readCount: [
          { required: true, message: "阅读数不能为空", trigger: "blur" }
        ]
        // pictureUrl: [
        //   { required: true, validator: validateUpload, trigger: "change" }
        // ]
      }
    };
  },
  mounted() {
    this.initData();
  },
  methods: {
    initData() {
      this.imgHeaders.Authorization = getToken();
      //上传图片链接
      this.uploadUrl = process.env.BASE_API + "/picture/upload";
      this.getLookList();
    },
    handleReset(name) {
      this.$refs[name].resetFields();
    },
    clearFiles() {
      this.$refs["upload"].clearFiles();
    },
    handleRemove(file, fileList) {
      this.newLookdata.pictureUrl = "";
    },
    handleAvatarSuccess(res, file) {
      this.newLookdata.pictureUrl = res.data;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getLookList();
    },
    //时间格式化
    formatterTime(t) {
      if (t) {
        const newTime = format("yyyy-MM-dd", new Date(t)).split(" ");
        return newTime;
      } else {
        return "";
      }
    },
    async getLookList() {
      this.dataTable.loading = true;
      this.searchLoading = true;
      const res = await fetchLookList({
        pageSize: this.limit,
        pageNo: this.currentPage,
        searchKey: this.searchInpt
      });
      this.searchLoading = false;
      this.dataTable.loading = false;
      this.dataTable.data = [];
      this.count = res.data.total;
      res.data.list.forEach(item => {
        const data = {};
        data.id = item.id;
        data.content = item.content;
        data.readCount = item.readCount;
        data.title = item.title;
        data.picUrl = item.picUrl;
        data.createTime = this.formatterTime(item.createTime);
        data.showAll = false;
        if (item.status === 0) {
          data.status = "正常";
        } else {
          data.status = "删除";
        }
        this.dataTable.data.push(data);
      });
    },
    async addLook(name) {
      const res = await fetchAddLook({
        title: this.newLookdata.title,
        content: this.newLookdata.content,
        linkUrl: this.newLookdata.linkUrl,
        pictureUrl: this.newLookdata.pictureUrl[0],
        readCount: this.newLookdata.readCount
      });
      if (res.status === 200) {
        this.addNewQA = false;
        this.getLookList();
        this.clearFiles();
        this.handleReset(name);
        this.$message({
          type: "success",
          message: "创建成功"
        });
      } else {
        this.$message({
          type: "error",
          message: "创建失败"
        });
      }
    },
    async delLook(id) {
      const res = await fetchDeleteLook({
        lookId: id,
        status: "9"
      });
      if (res.status === 200) {
        this.getLookList();
        this.$message({
          type: "success",
          message: "删除成功"
        });
      } else {
        this.$message({
          type: "error",
          message: "删除失败"
        });
      }
    },
    search() {
      this.currentPage = 1;
      this.pageshow = false;
      this.getLookList();
      this.$nextTick(() => {
        this.pageshow = true;
      });
    },
    showImgDialogBox(img) {
      console.log(img);
      if (img) {
        this.showImgDialog = true;
        this.picture = img.split(",");
      } else {
        this.$message({
          type: "error",
          message: "无图片"
        });
      }
    },
    newQA() {
      this.addNewQA = true;
    },
    handleSubmit(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          this.addLook(name);
        }
      });
    },
    delQA(id) {
      this.$confirm("是否删除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.delLook(id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    }
  },
  components: {
    Table
  }
};
</script>
